package com.flyou.ccnucenter.ui.activity.login;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.flyou.ccnucenter.Constant;
import com.flyou.ccnucenter.R;
import com.flyou.ccnucenter.domain.MyUser;
import com.flyou.ccnucenter.ui.activity.BaseActivity1;
import com.flyou.ccnucenter.ui.activity.MainActivity;
import com.flyou.ccnucenter.ui.activity.webView.WebViewActivity;
import com.flyou.ccnucenter.utils.BmobErrorCodeUtils;
import com.flyou.ccnucenter.utils.Md5Parser;
import com.flyou.ccnucenter.utils.RegexPatternUtils;
import com.flyou.ccnucenter.utils.SPUtils;
import com.flyou.ccnucenter.utils.TextEmptyUtil;
import com.flyou.ccnucenter.widget.ClearEditText;

import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobSMS;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.RequestSMSCodeListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.VerifySMSCodeListener;

public class RegistActivity extends BaseActivity1 implements View.OnClickListener {

    private RelativeLayout mTitlebarRlBack;
    private TextView mTitlebarTvTitle;
    private com.flyou.ccnucenter.widget.ClearEditText registetusername;
    private com.flyou.ccnucenter.widget.ClearEditText registetphone;
    private com.flyou.ccnucenter.widget.ClearEditText registetemail;
    private com.flyou.ccnucenter.widget.ClearEditText registetpassword;
    private com.flyou.ccnucenter.widget.ClearEditText registetrepassword;
    private android.widget.CheckBox registcbagreeprotocol;
    private android.widget.TextView registtvprotocol;
    private android.widget.Button registbtnextstep;

    private ClearEditText et_verifition_number;
    private Button bt_get_verifition_code;
    //    短信是否验证成功
    private boolean isRegistSMS = false;

    @Override
    protected void initView() {
        setContentView(R.layout.activity_regist);

        mTitlebarRlBack = (RelativeLayout) findViewById(R.id.titlebar_rl_back);
        mTitlebarTvTitle = (TextView) findViewById(R.id.titlebar_tv_title);

        this.registbtnextstep = (Button) findViewById(R.id.regist_bt_next_step);
        this.registtvprotocol = (TextView) findViewById(R.id.regist_tv_protocol);
        this.registcbagreeprotocol = (CheckBox) findViewById(R.id.regist_cb_agree_protocol);
        this.registetrepassword = (ClearEditText) findViewById(R.id.regist_et_repassword);
        this.registetpassword = (ClearEditText) findViewById(R.id.regist_et_password);
        this.registetemail = (ClearEditText) findViewById(R.id.regist_et_email);
        this.registetphone = (ClearEditText) findViewById(R.id.regist_et_phone);
        this.registetusername = (ClearEditText) findViewById(R.id.regist_et_username);
        et_verifition_number = (ClearEditText) findViewById(R.id.et_verifition_number);
        bt_get_verifition_code = (Button) findViewById(R.id.bt_get_verifition_code);
    }

    @Override
    protected void initDate() {
        mTitlebarTvTitle.setText("用户注册");
    }

    @Override
    protected void setListener() {
        mTitlebarRlBack.setOnClickListener(this);
        registbtnextstep.setOnClickListener(this);
        registtvprotocol.setOnClickListener(this);
        bt_get_verifition_code.setOnClickListener(this);


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.titlebar_rl_back:
                finish();
                break;
            case R.id.regist_tv_protocol:

                Intent intent = new Intent(RegistActivity.this, WebViewActivity.class);
                intent.putExtra("title", "注册协议");
                intent.putExtra("url", Constant.BASE_URL + Constant.REGISTRATION_AGREEMENT);
                startActivity(intent);
                break;
            case R.id.bt_get_verifition_code:
                if (!RegexPatternUtils.isMobile(registetphone.getText().toString().trim())) {
                    Toast.makeText(this, "手机号格式有误，请重新输入", Toast.LENGTH_SHORT).show();
                    return;
                }
                postVeritftionCode();


                break;
            case R.id.regist_bt_next_step:
                if (verifitionRegist()) {
                    String phone = registetphone.getText().toString().trim();
                    String code = et_verifition_number.getText().toString().trim();
                    if (isRegistSMS) {
                        regist();
                    } else {
                        VerifitionSmsCode(phone, code);
                    }
                }

                break;

        }


    }

    /*
    * 验证验证码
    * */
    private void VerifitionSmsCode(String phone, String code) {
        mProgressDialog = ProgressDialog.show(RegistActivity.this, null, "正在提交", false, false);
        final Boolean[] flag = {false};
        BmobSMS.verifySmsCode(this, phone, code, new VerifySMSCodeListener() {
            @Override
            public void done(BmobException ex) {
                mProgressDialog.dismiss();
                // TODO Auto-generated method stub
                if (ex == null) {//短信验证码已验证成功
                    isRegistSMS = true;
                    regist();
                } else {
                    isRegistSMS = false;
                    Toast.makeText(RegistActivity.this, "验证码有误", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    /*
    * 发送验证码
    * */
    private void PostVerifitionCode(String phone) {
        bt_get_verifition_code.setText("正在发送验证码");
        bt_get_verifition_code.setEnabled(false);
        BmobSMS.requestSMSCode(RegistActivity.this, phone, "用户注册", new RequestSMSCodeListener() {

            @Override
            public void done(Integer smsId, BmobException ex) {
                mProgressDialog.dismiss();
                if (ex == null) {
                    new MyCount(60000, 1000).start();
                    Toast.makeText(RegistActivity.this, "验证码发送成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(RegistActivity.this, ex.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    /*
    * 注册
    * */
    private void regist() {
        final String userName = registetusername.getText().toString().trim();
        final String phone = registetphone.getText().toString().trim();
        String password = Md5Parser.md5Parser(registetrepassword.getText().toString().trim());
        final MyUser myUser = new MyUser();

        myUser.setDepartment("");
        myUser.setGrade("");
        myUser.setUsername(userName);
        myUser.setPassword(password);
        myUser.setMobilePhoneNumberVerified(true);
        myUser.setMobilePhoneNumber(phone);
        myUser.setHeadImage("");
        myUser.signUp(RegistActivity.this, new SaveListener() {
            @Override
            public void onSuccess() {
                Toast.makeText(RegistActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                SPUtils.put(RegistActivity.this, "userName", userName);
                SPUtils.put(RegistActivity.this, "phone", phone);
                SPUtils.put(RegistActivity.this, "email", TextEmptyUtil.SetEmptyTo(myUser.getEmail()) );
                SPUtils.put(RegistActivity.this, "objectId", myUser.getObjectId());
                SPUtils.put(RegistActivity.this, "grade", TextEmptyUtil.SetEmptyTo(myUser.getGrade()));
                SPUtils.put(RegistActivity.this, "department",TextEmptyUtil.SetEmptyTo(myUser.getDepartment()));
                Intent intent = new Intent(RegistActivity.this, MainActivity.class);
                startActivity(intent);
            }

            @Override
            public void onFailure(int i, String s) {
                if (i == 401) {
                    Toast.makeText(RegistActivity.this, "该手机号已经注册，如果是您本人注册，您可以通过找回密码功能找回账号", Toast.LENGTH_SHORT).show();
                } else {
                    String message = BmobErrorCodeUtils.getMessage(i, s);
                    Toast.makeText(RegistActivity.this, message, Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    private boolean verifitionRegist() {
        if (!RegexPatternUtils.isMobile(registetphone.getText().toString().trim())) {
            Toast.makeText(this, "手机号格式有误，请重新输入", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (!RegexPatternUtils.isUsername(registetusername.getText().toString().trim())) {
            Toast.makeText(this, "用户名格式有误，2到10个汉字字母组合", Toast.LENGTH_SHORT).show();
            return false;
        }

//        if (!RegexPatternUtils.isEmail(registetemail.getText().toString().trim())) {
//            Toast.makeText(this, "邮箱格式有误，请重新输入", Toast.LENGTH_SHORT).show();
//            return false;
//        }
        if (TextUtils.isEmpty(registetpassword.getText().toString().trim())) {
            Toast.makeText(this, "密码不能为空,请输入", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (!registetpassword.getText().toString().trim().equals(registetrepassword.getText().toString().trim())) {
            Toast.makeText(this, "两次密码输入不一致,请重新输入", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (!registcbagreeprotocol.isChecked()) {
            Toast.makeText(this, "请确认同意注册协议", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (et_verifition_number.getText().toString().trim().length() != 6) {
            Toast.makeText(this, "请输入6位数字验证码", Toast.LENGTH_SHORT).show();
        }
        return true;
    }

    /*
    * 发送验证码
    * */
    public void postVeritftionCode() {
        mProgressDialog = ProgressDialog.show(RegistActivity.this, null, "正在提交数据", false, false);

        BmobQuery<MyUser> query = new BmobQuery<MyUser>();
        query.addWhereEqualTo("phone", registetphone.getText().toString().trim());
        query.findObjects(RegistActivity.this, new FindListener<MyUser>() {

            @Override
            public void onSuccess(List<MyUser> list) {

                if (list.size() > 0) {
                    mProgressDialog.dismiss();
                    Toast.makeText(RegistActivity.this, "该手机号已经注册", Toast.LENGTH_SHORT).show();
                } else {
                    PostVerifitionCode(registetphone.getText().toString().trim());
                }
            }

            @Override
            public void onError(int i, String s) {
                mProgressDialog.dismiss();
                String message = BmobErrorCodeUtils.getMessage(i, s);
                Toast.makeText(RegistActivity.this, message, Toast.LENGTH_SHORT).show();

            }
        });

    }


    /*
    * 自定义定时器
    * */
    class MyCount extends CountDownTimer {
        /**
         * @param millisInFuture    总时间
         * @param countDownInterval 间隔事件
         */
        public MyCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            bt_get_verifition_code.setText("重新发送 " + (int) millisUntilFinished / 1000);
            bt_get_verifition_code.setEnabled(false);
        }

        @Override
        public void onFinish() {
            bt_get_verifition_code.setText("获取验证码");
            bt_get_verifition_code.setEnabled(true);

        }
    }
}
